/**
 * create by young (young2f@outlook.com) on 2020/9/12
 */


'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {Button, Card, Col, Drawer, Dropdown, Form, Menu, Popconfirm, Row, Select, Statistic, Table} from 'antd';

import styles from '../index.less';
import ViewTitle from '../../components/ViewTitle';
import FormBase from '../../components/Base/FormBase';
import notify from "../../components/NotificationExtra";
import {FormField, ModalView, SearchForm} from 'antd-extra';
import moment from 'moment';
import 'moment/locale/zh-cn';
import ModalSalesOrderDetail from "./modal/ModalSalesOrderDetail";
import ModalPaid from "./modal/ModalPaid";
import {exportExcel} from "../../utils/excelUtils";
import ModalCreateOrEditSalesOrder from "./modal/ModalCreateOrEditSalesOrder";
import Icon from "antd/es/icon";
import ModalStatistics from "./modal/ModalStatistics";

moment.locale('zh-cn');

const _ = require('lodash');
const {Option} = Select;
const table = 'SalesOrder';
const title = '订单';

@Form.create()
@connect(({
            user,
            global,
            customer,
            sales,
            dict,
            material,
            store
          }) => ({...user, ...global, ...dict, ...material, ...customer, ...sales, ...store}))
export default class Index extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {dispatch} = this.props;
    const payload = this.props.form.getFieldsValue();
    if (!payload.projectType) payload["projectType"] = {$ne: "租用"};
    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table}
    });

    this.props.dispatch({
      type: 'sales/findMany',
      payload
    });
    dispatch && dispatch({
      type: 'dict/findMany',
      payload: {type: 'division'}
    });
    this.props.dispatch({
      type: 'customer/findMany',
      payload: {}
    });
    this.props.dispatch({
      type: 'material/findMany',
      payload: {}
    });
  }

  onDelete = record => {
    const {code} = record;
    this.props.dispatch({
      type: 'sales/deleteOne',
      payload: {code}
    })
      .then(res => {
        this.requestReturn(res);
        this.componentDidMount();
      });
  };
  onCreate = async () => {
    const {model = {}, dispatch, customers = [], materials = []} = this.props;
    const code = this.getCode('SAL');
    const values = {code};
    ModalView.open(ModalCreateOrEditSalesOrder, {
      title: '新建订单',
      width: '1580px',
      maskClosable: false
    }, {
      values,
      model,
      customers,
      materials,
      dispatch,
      table,
      cols: 4,
      callback: (data) => {
        data.table = table;
        data.reviewStatus = '待审核';
        this.props.dispatch({
          type: 'sales/create',
          payload: data
        }).then(res => {
          this.requestReturn(res);
          this.componentDidMount();
        });
      }
    });
  };
  onCopy = async (values) => {
    const _values = _.cloneDeep(values);
    _values.code = this.getCode('SAL');
    delete _values["_id"];
    const {dispatch, customers = [], materials = []} = this.props;
    const model = this.props[`${table}Model`];
    let _title = `复制${title}`;
    _.map(model, (item, key) => {
      item.defaultValue = _values[key];
    });

    ModalView.open(ModalCreateOrEditSalesOrder, {
      title: _title,
      width: '1580px',
      maskClosable: false
    }, {
      model, customers, materials,
      values: _values,
      dispatch: dispatch,
      table,
      title: _title,
      cols: 4,
      callback: (data) => {
        data.table = table;
        data.reviewStatus = '待审核';
        delete data['createdTs'];
        this.props.dispatch({
          type: 'sales/create',
          payload: data
        }).then(res => {
          this.requestReturn(res);
          this.componentDidMount();
        });
      }
    });
  };
  onEdit = async (values) => {
    const {dispatch, customers = [], materials = []} = this.props;
    const model = this.props[`${table}Model`];
    let _title = `编辑${title}`;
    _.map(model, (item, key) => {
      item.defaultValue = values[key];
    });
    const _record = _.cloneDeep(values);
    ModalView.open(ModalCreateOrEditSalesOrder, {
      title: _title,
      width: '1580px',
      maskClosable: false
    }, {
      model, customers, materials,
      values,
      dispatch: dispatch,
      table, cols: 4,
      title: _title,
      disabledProps: ['code'],
      callback: (data) => {
        _.merge(_record, data);
        _record.table = table;

        this.props.dispatch({
          type: 'sales/updateOne',
          payload: _record
        }).then(res => {
          this.requestReturn(res);
          this.componentDidMount();
        });
      }
    });
  };
  paid = values => {
    ModalView.open(ModalPaid, {
      title,
      width: '920px'
    }, {
      values,
      inInbound: true,
      callback: (record) => {
        const {paid} = record;
        const {code} = values;
        this.props.dispatch({
          type: 'procure/updateOne',
          payload: {code, paid, paidDate: moment().format('YYYY-MM-DD hh:mm:ss')}
        }).then(res => {
          this.componentDidMount();
        });
      }
    });
  };

  menu = record => {
    return (
      <Menu>
        <Menu.Item disabled={record.reviewStatus === '同意'}>
          <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '同意'}
             onClick={() => this.onEdit(record)}>编辑</a>
        </Menu.Item>
        <Menu.Item>
          <a style={{marginRight: '6px'}}
             onClick={() => this.onCopy(record)}>复制</a>
        </Menu.Item>
      </Menu>);
  };

  getTableCols = () => {
    const model = this.props[`${table}Model`];
    const temp = [];
    temp.push({
      title: '采购单价状态', dataIndex: 'priceStatus', key: 'priceStatus', render: (value, record) => {
        const {prods = []} = record;
        let isOk = true;
        _.map(prods, prod => {
          const {materials} = prod;
          _.map(materials, material => {
            const {usedMaterialRecord} = material;
            _.map(usedMaterialRecord, (item, key) => {
              const {price = 0} = item;
              if (price === 0) isOk = false;
            })
          });
        });
        return isOk ? <div style={{color: "#2b2"}}>OK</div> : <div style={{color: "#f22"}}>待补充</div>;
      }
    });
    temp.push(...this.getTableColumns(model));
    _.remove(temp, item => item.dataIndex === 'rentStartDate');
    _.remove(temp, item => item.dataIndex === 'rentEndDate');
    _.remove(temp, item => item.dataIndex === 'rentReturnDate');
    temp.push(
      {
        title: '操作', dataIndex: 'operation', key: 'operation',
        width: 160, fixed: 'right',
        render: (value, record) => {
          return (
            <span>
           {<a style={{marginRight: '6px'}}
               onClick={() => this.setState({showDetail: true, record})}>详情</a>}

              {/*{*/}
              {/*  <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '同意'}*/}
              {/*     onClick={() => this.onEdit(record)}>编辑</a>*/}
              {/*}*/}
              {<Popconfirm
                title="确认删除"
                onConfirm={() => this.onDelete(record)}
                okText="是"
                cancelText="否"

              >
                <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '同意'}>删除</a>
              </Popconfirm>}
              <Dropdown overlay={this.menu(record)}>
              <a className="ant-dropdown-link">
                更多 <Icon type="down"/>
              </a>
            </Dropdown>
            </span>
          );
        }
      });
    return temp;

  };

  getSearchFields = () => {
    const model = this.props[`${table}Model`];
    if (!model) return [];
    const arr = [];
    this.getSearchField(arr, model, "");
    const {prods} = model;

    this.getSearchField(arr, prods, "prods.");
    const {materials} = prods;
    this.getSearchField(arr, materials, "prods.materials.");
    arr.push(<FormField
      label={"是否开票"}
      name={"isKP"}
      key={"isKP"}
    >
      <Select allowClear>{[<Option value={"已开票"}>{"已开票"}</Option>,
        <Option value={"未开票"}>{"未开票"}</Option>]}</Select>
    </FormField>);
    arr.push(<FormField
      label={"是否发货"}
      name={"isFH"}
      key={"isFH"}
    >
      <Select allowClear>{[<Option value={"已发货"}>{"已发货"}</Option>,
        <Option value={"未发货"}>{"未发货"}</Option>]}</Select>
    </FormField>);
    return arr;
  };


  export = () => {
    this.props.dispatch({
      type: 'sales/exportExcel',
      payload: this.getSearchPayload()
    }).then(res => {
      if (res) {
        const {result = {}} = res;
        const {header, data} = result;
        exportExcel(header, data, '订单');
      }
    });
  };

  render() {
    const {sales = {}, _notify, form} = this.props;
    const {record = {}, showDetail, showStatistics} = this.state;

    if (_notify && this.state._notify !== _notify) {
      notify(_notify);
      this.state._notify = _notify;
    }

    const {amount, count, array} = sales;
    return (
      <Form className={styles.content}>
        <ViewTitle
          title={`${title}列表`}
          level={1}
          actions={[
            <Button type="primary" onClick={() => this.onCreate(undefined)}>添加</Button>
          ]}></ViewTitle>
        <SearchForm
          style={{marginLeft: '6px', marginRight: '6px'}}
          onSearch={() => {
            this.state.current = 1;
            this.componentDidMount();
          }}
          onReset={this.handleReset}
          cols={4}
          min={8}
          expandText="展开"
          form={form}
        >
          {this.getSearchFields()}
        </SearchForm>
        <div style={{background: '#ECECEC', padding: '30px'}}>
          <Row gutter={16}>
            <Col span={10}>
              <Card>
                <Statistic
                  title="订单商品总数量"
                  value={count}
                  precision={2}
                  valueStyle={{color: '#3f8600'}}
                  suffix="KG"
                />
              </Card>
            </Col>
            <Col span={10}>
              <Card>
                <Statistic
                  title="订单商品总金额"
                  value={amount}
                  precision={2}
                  valueStyle={{color: '#cf1322'}}
                  suffix="元"
                />
              </Card>
            </Col>
            <Col span={4}>
              <Card
                onClick={() => {
                  this.setState({showStatistics: true});
                }}
              >
                <Statistic
                  title="更多"
                  value={'点击查看'}
                  precision={3}
                  valueStyle={{color: '#35f'}}
                />

              </Card>
            </Col>
          </Row>
        </div>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.getTableCols()}
          dataSource={array}
          scroll={{x: true}}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
          //  scroll={{ x: 1300 }}
        ></Table>

        {showDetail && <Drawer
          visible={showDetail}
          title={`${title}详情`}
          placement="left"
          width={'80%'}
          style={{padding: 0}}
          // maskClosable={false}
          onClose={() => {
            this.setState({showDetail: false});
            this.componentDidMount();
          }}
        >
          <ModalSalesOrderDetail
            values={record}
          > </ModalSalesOrderDetail>
        </Drawer>}

        {showStatistics && <Drawer
          visible={showStatistics}
          title={`统计`}
          placement="left"
          width={'80%'}
          style={{padding: 0}}
          // maskClosable={false}
          onClose={() => {
            this.setState({showStatistics: false});
            this.componentDidMount();
          }}
        >
          <ModalStatistics
            values={array}
          > </ModalStatistics>
        </Drawer>}
      </Form>
    );
  }
}


